<template>
   <s-card title="优先级设置" style="width: 100%">
      <div>
         <table>
            <thead>
               <tr class="info">
                  <th width="100px">信号源</th>
                  <th>优先级(从上到下，优先级从高到低)</th>
               </tr>
            </thead>
            <tbody>
               <tr v-for="(value,index) in list" :key="value">
                  <td>{{ TextMaps[value] }}</td>
                  <td><s-icon type="icon-arrow-down" style="font-size: 24px;cursor:pointer" @click="handleChange(value,index)"/></td>
               </tr>
            </tbody>
         </table>
      </div>
      <template #footer>
         <s-button type="primary" @click="handleSubmit">应用</s-button>
      </template>
   </s-card>
</template>

<script lang="ts" setup>
import { SCard, SButton, SIcon, Message } from "@/components"
import { onBeforeMount, ref, toRaw } from "vue"
import { setPriority, getPriority } from "@/request"

const TextMaps = {
   1: "IP/4G",
   4: "外部信号",
   3: "U 盘"
}

const list = ref<Array<number>>([])

const getInit = () => {
   getPriority().then((data) => {
      list.value = data.signlist
   })
}

const handleChange = (value:number, index:number) => {
   // 如果是最后一个，没有变化
   if (index === list.value.length - 1) {
      return
   }
   const newList = list.value
   const nextValue = newList[index + 1]
   newList[index] = nextValue
   newList[index + 1] = value
   list.value = newList
}

const handleSubmit = () => {
   setPriority({
      signlist: toRaw(list.value)
   }).then(() => {
      Message.success("设置成功")
      getInit()
   })
}

onBeforeMount(() => {
   getInit()
})
</script>

<style scoped lang="less">
   table {
      text-align: left;
      thead {
         background: aliceblue;
      }
      tr {
         height: 30px;
         line-height: 30px;
         td,
         th {
            padding: 2px 8px;
            border: 1px solid #eee;
         }
      }
   }
</style>
